package zl_service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/goravel/framework/support/carbon"
	"goravel/app/models"
	"io/ioutil"
	"net/http"
)

const (
	ORDER_URL = "/zl.open.api.oms.pos.createordercommon.v5/1.0.0/action"
)

type OrderService struct {
}

type OrderParams struct {
	AppKey     string                  `json:"appkey"`
	Signtime   string                  `json:"signtime"`
	Ticketcode string                  `json:"ticketcode" comment:"销售单流水号"`
	OrderNo    string                  `json:"orderno" comment:"销售单业务单号"`
	Saletime   string                  `json:"saletime" comment:"销售时间 无则传当前时间"`
	Total      string                  `json:"total" comment:"销售单总金额"`
	Paytotal   string                  `json:"paytotal" comment:"支付总额"`
	Commoditys []models.OrderCommodity `json:"commoditys" comment:"商品行"`
	Paydetails []models.PayDetail      `json:"paydetails" comment:"支付行"`
}

func (b *OrderService) CreateOrder(order models.Order) error {
	url := BASE_URL + ORDER_URL
	client := &http.Client{}
	orderParams := OrderParams{
		AppKey:     APP_KEY,
		Signtime:   carbon.NewDateTime(carbon.Now()).Format("Y-m-d H:i:s"),
		Ticketcode: order.Ticketcode,
		OrderNo:    order.Orderno,
		Saletime:   carbon.NewDateTime(carbon.Now()).Format("Y-m-d H:i:s"),
		Total:      order.Total,
		Paytotal:   order.Paytotal,
		Commoditys: order.Commoditys,
		Paydetails: order.Paydetails,
	}

	bodyBytes, _ := json.Marshal(orderParams)
	stringToSign := fmt.Sprintf("%s&appsecret=%s", string(bodyBytes), APP_SECRET)
	upperSign := ComputeMD5AndToUpper(stringToSign)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Request-Sign", upperSign)
	body, err := client.Do(req)
	if err != nil {
		return err
	}
	//将body
	res, err := ioutil.ReadAll(body.Body)
	fmt.Println(string(res))
	return nil
}
